package com.hd.trans.utils

import android.content.res.AssetManager
import android.os.Build
import android.os.Environment
import android.text.TextUtils
import com.hd.trans.R
import com.hd.trans.extension.ioExecute
import com.hd.trans.extension.isAudio
import com.hd.trans.extension.isExcel
import com.hd.trans.extension.isHtml
import com.hd.trans.extension.isImage
import com.hd.trans.extension.isPPT
import com.hd.trans.extension.isPdf
import com.hd.trans.extension.isText
import com.hd.trans.extension.isWord
import com.hd.trans.network.bean.RCFileType
import com.hd.trans.share.Md5Util
import com.hd.trans.ui.base.AppContextProvider
import okhttp3.ResponseBody
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.UUID

object FileUtilsKotlin {
    private const val PROGRAME_NAME = "/HDOCRFiles"

    private val DATE_FORMAT by lazy {
        SimpleDateFormat("yyyyMMddHHmmssSS", Locale.getDefault())
    }

    fun isValidFile(checkPath: String?): Boolean {
        return if (!TextUtils.isEmpty(checkPath)) {
            val file = File(checkPath)
            file.exists() && file.length() > 0
        } else {
            false
        }
    }
    /**
     * 将asset文件保存为指定文件
     */
    fun assetRes2File(
        am: AssetManager, assetFile: String, dstFile: String,
    ): Boolean {
        if (isValidFile(dstFile)) {
            return true
        }
        if (TextUtils.isEmpty(dstFile)) {
            return false
        }
        var os: OutputStream? = null
        var file: File? = null
        try {
            os = FileOutputStream(dstFile)
            file = File(dstFile)
            val pBuffer = ByteArray(1024)
            var nReadLen: Int
            if (null == am) {
                return false
            }
            val `is` = am.open(assetFile!!)
            while (`is`.read(pBuffer).also { nReadLen = it } != -1) {
                os.write(pBuffer, 0, nReadLen)
            }
            os.flush()
            os.close()
            `is`.close()
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            //new File(dstFile).delete();
            if (file != null && file.exists()) {
                file.delete()
            }
            return false
        } catch (e: IOException) {
            e.printStackTrace()
            if (file != null && file.exists()) {
                file.delete()
            }
            return false
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        } finally {
            try {
                os?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return true
    }

    fun getUniqueName(name: String): String {
        if (TextUtils.isEmpty(name) || !name.contains(".")) {
            return "${UUID.randomUUID()}.temp"
        }
        val suffix: String = name.substring(name.lastIndexOf("."))
        return "${UUID.randomUUID()}${suffix}"
    }

    fun isPdfFile(path: String): Boolean {
        return getExtension(path).toLowerCase(Locale.ROOT) == RCFileType.PDF.suffix
    }

    fun getExtension(uri: String?): String {
        if (uri == null) {
            return ""
        }
        val dot = uri.lastIndexOf(".")
        return if (dot >= 0) {
            uri.substring(dot + 1)
        } else {
            // No extension.
            ""
        }
    }


    /**
     * 获取文件切片路径
     */
    fun getSplitTempFilePath(file: File, index: Int): String {
        //获取file的类型
        val split = file.name.split(".")
        val inType = split[split.size - 1]

        val fileRoot = getCacheRoot()
        val parent = File(fileRoot, "temp")
        if (!parent.exists()) {
            parent.mkdirs()
        }
        val tempName = "${Md5Util.md5(file.name)}${index}.$inType"
        val tempFile = File(parent, tempName)
        if (tempFile.exists()) {
            tempFile.delete()
        }
        return tempFile.absolutePath
    }

    /**
     * 获取项目缓存目录
     */
    private fun getCacheRoot(): File {
        val appContext = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            AppContextProvider.getContext().filesDir
        else
            Environment.getExternalStorageDirectory()
        return appContext
    }

    /**
     * 项目媒体类存储路径
     */
    fun getMediaOutput(): File {
        val root = getCacheRoot()
        val output = File(root, "/${PROGRAME_NAME}/OcrCamera")
        if (!output.exists()) {
            output.mkdirs()
        }
        return output
    }

    fun getDownloadOutPut(): File {
        val root = getCacheRoot()
        val output = File(root, "/Download")
        if (!output.exists()) {
            output.mkdirs()
        }
        return output
    }

    fun getDownloadFileName(url: String, fileName: String): String {
        val file = getDownloadOutPut()
        val index = url.lastIndexOf(".")
        val suffix =
            if (index == -1) {
                ".hdocr"
            } else {
                url.substring(index)
            }
        val name = if (!TextUtils.isEmpty(fileName)) {
            "${fileName}$suffix"
        } else {
            "${DATE_FORMAT.format(System.currentTimeMillis())}$suffix"
        }
        return "${file.absolutePath}/$name"
    }

    suspend fun writeResponseBodyToDisk(
        body: ResponseBody,
        url: String,
        name: String,
    ): File {
        return ioExecute {
            val path = writeResponseBodyToDisk2(body, url,name)
            File(path)
        }

    }

    private fun writeResponseBodyToDisk2(body: ResponseBody, url: String, name: String = ""): String {
        var inputStream: InputStream? = null
        var outputStream: OutputStream? = null
        return try {
            val futureStudioIconFile = getDownloadFileName(url, name)
            try {
                val fileReader = ByteArray(4096)
                val fileSize = body.contentLength()
                var fileSizeDownloaded: Long = 0
                inputStream = body.byteStream()
                outputStream = FileOutputStream(futureStudioIconFile)
                while (true) {
                    val read = inputStream.read(fileReader)
                    if (read == -1) {
                        break
                    }
                    outputStream.write(fileReader, 0, read)
                    fileSizeDownloaded += read.toLong()
                }
                outputStream.flush()
            } finally {
                inputStream?.close()
                outputStream?.close()
            }
            futureStudioIconFile
        } finally {

            inputStream?.close()
            outputStream?.close()
        }
    }


    @JvmStatic
    fun getFileIcon(filePath: String): Int {
        return when{
            filePath.isAudio() -> R.mipmap.ic_doc_audio
            filePath.isImage() -> R.mipmap.ic_doc_image
            filePath.isPPT() -> R.mipmap.ic_doc_ppt
            filePath.isPdf() -> R.mipmap.ic_doc_pdf
            filePath.isWord() -> R.mipmap.ic_doc_docx
            filePath.isExcel() -> R.mipmap.ic_doc_xls
            filePath.isText() -> R.mipmap.ic_doc_txt
            filePath.isHtml() -> R.mipmap.ic_doc_html
            //filePath.isVideo() -> R.mipmap.ic_doc_video
            else -> R.mipmap.ic_doc_default
        }
    }
}